package bb.lanxing.adapter;

import static bb.lanxing.activity.routebook.RouteBookInfoActivity.REQUEST_TYPE_ROUTE_BOOK_INFO;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;
import org.litepal.LitePal;

import com.besall.allbase.bluetooth.service.Protocol.ProtocolService;
import com.besall.allbase.common.utils.FileUtils;
import com.besall.allbase.view.activity.chipstoollevel4.protocol.ProtocolPresenter;

import android.app.Activity;
import android.bluetooth.BluetoothProfile;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;

import bb.lanxing.App;
import bb.lanxing.R;
import bb.lanxing.activity.base.BaseActivity;
import bb.lanxing.activity.routebook.RouteBookImportActivity;
import bb.lanxing.activity.sport.SportActivity;
import bb.lanxing.lib.devices.sgsettingentity.routebook.Route;
import bb.lanxing.lib.devices.sgsettingentity.routebook.Routebooks;
import bb.lanxing.manager.SharedManager;
import bb.lanxing.model.database.RouteBook;
import bb.lanxing.model.database.RouteBookInfo;
import bb.lanxing.network.BiCiCallback;
import bb.lanxing.network.MyHttpClient;
import bb.lanxing.util.CommonUtil;
import bb.lanxing.util.Log;
import bb.lanxing.util.RouteBookUtil;
import bb.lanxing.util.SpliceBitmapUtil;
import bb.lanxing.util.SportTypeResUtil;
import bb.lanxing.util.image.GlideUtils;
import bb.lanxing.view.BiciAlertDialogBuilder;
import bb.lanxing.view.UserAvatarView;
import gov.nist.core.Separators;

public class RouteBookNormalAdapter extends LoadMoreAdapter {
    private final Context context;
    private final List<RouteBook> routeBookList;
    private boolean isNeedChoose = false;
    private boolean fromSportMap = true;
    private boolean update;
    private boolean delete;
    private long chooseId = -1;
    private boolean enableImport;

    public RouteBookNormalAdapter(Context context, List<RouteBook> list) {
        this.routeBookList = list;
        this.context = context;
    }

    public void setEnableImport(boolean enableImport) {
        this.enableImport = enableImport;
    }

    public void setUpdate(boolean update) {
        this.update = update;
    }

    public void setDelete(boolean delete) {
        this.delete = delete;
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    public void setIsNeedChoose(boolean z) {
        this.isNeedChoose = z;
    }

    public void setChooseId(long j) {
        this.chooseId = j;
    }

    public void setFromSportMap(boolean z) {
        this.fromSportMap = z;
    }

    @Override
    public View getView(final int i, View view, ViewGroup viewGroup) {
        ViewHolder viewHolder;
        View view2;
        if (this.loadMoreEnabled && !this.loadingMore && this.onLoadEndListener != null
                && i >= this.routeBookList.size() - 2) {
            this.loadingMore = true;
            this.onLoadEndListener.onLoadEnd();
        }
        final RouteBook routeBook = this.routeBookList.get(i);
        if (view == null) {
            view2 = LayoutInflater.from(this.context).inflate(R.layout.item_lushu_list, viewGroup, false);
            viewHolder = new ViewHolder(view2);
            view2.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) view.getTag();
            view2 = view;
        }
        // if (App.getContext().isDebugMode()) {
        // TextView type = viewHolder.tvType;
        // type.setVisibility(View.VISIBLE);
        // if (routeBook.getSourceType() == TYPE_BAIDU) {
        // type.setText("百度路书");
        // } else if (routeBook.getSourceType() == TYPE_IMPORT) {
        // type.setText("GPX导入路书");
        // }
        // }

        String title = routeBook.getTitle();
        if (TextUtils.isEmpty(title)) {
            title = routeBook.getFileName();
        }
        if (title == null) {
            title = "";
        }
        String imageUrl = routeBook.getImageUrl();
        Log.i("getView i = " + i + ",imageUrl = " + imageUrl);
        if (!TextUtils.isEmpty(imageUrl)) {
            GlideUtils.companion.loadImage(viewHolder.ivMap.getContext(), imageUrl, viewHolder.ivMap,
                    R.drawable.bg_summary_default_map, R.drawable.bg_summary_default_map);
        } else {
            viewHolder.ivMap.setImageResource(R.drawable.bg_summary_default_map);
        }
        viewHolder.userAvatarView.setAvatarMode(UserAvatarView.AVATAR_SIZE_24);
        viewHolder.userAvatarView.setAvatarForUrl(routeBook.getUserAvatar());
        viewHolder.userAvatarView.goToUserInfo(routeBook.getUserId());
        viewHolder.ivSportType.setImageResource(SportTypeResUtil.getRoundTypeIcon(routeBook.getSport()));
        viewHolder.tvTitle.setText(title);
        viewHolder.tvDistance.setText(CommonUtil.getFormatDistance(routeBook.getDistance()));
        viewHolder.tvComment.setText(String.valueOf(routeBook.getCommentCount()));
        viewHolder.tvDownload.setText(String.valueOf(routeBook.getDownloadCount()));
        Drawable generateLushuFeature =
                SpliceBitmapUtil.generateLushuFeature(this.context, !TextUtils.isEmpty(routeBook.getThreedLushu()),
                        routeBook.getSimilarityNum() > 0, routeBook.isCollected(), routeBook.getServerType() == 2,
                        !routeBook.isUploadEnable(), routeBook.getCaTdfLevel());
        viewHolder.ivTypeIcons.setImageDrawable(generateLushuFeature);
        viewHolder.ivTypeIcons.setVisibility(generateLushuFeature != null ? View.VISIBLE : View.GONE);
        if (update) {
            if (routeBook.getUserId() > 0 && SharedManager.getInstance().getUserId() > 0) {
                if (TextUtils.isEmpty(imageUrl)) {
                    viewHolder.tvUpdate.setVisibility(View.VISIBLE);
                } else {
                    viewHolder.tvUpdate.setVisibility(View.GONE);
                }
            }
        } else {
            viewHolder.tvUpdate.setVisibility(View.GONE);
        }
        viewHolder.cbCheck.setChecked(this.chooseId == routeBook.getServerId());
        viewHolder.cbCheck.setOnCheckedChangeListener((compoundButton, z) -> {
            Intent intent = new Intent();
            intent.putExtra(SportActivity.EXTRA_LUSHU_ID, routeBook.getServerId());
            ((Activity) RouteBookNormalAdapter.this.context).setResult(Activity.RESULT_OK, intent);
            ((Activity) RouteBookNormalAdapter.this.context).finish();
        });
        viewHolder.ivDelete.setVisibility(this.delete ? View.VISIBLE : View.GONE);
        checkIfNotExistOnRouteBooks(routeBook.getServerId(), viewHolder.ivDelete);
        viewHolder.cbCheck.setVisibility(this.isNeedChoose ? View.VISIBLE : View.GONE);
        viewHolder.ivDelete.setOnClickListener(view3 -> showDeleteDialog(i));
        viewHolder.btnImport.setVisibility(this.enableImport ? View.VISIBLE : View.GONE);
        viewHolder.btnImport.setOnClickListener(view3 -> importRouteBook(routeBook.getServerId()));
        TextView textView = viewHolder.tvLushuId;
        textView.setText(Separators.POUND + routeBook.getServerId());
        viewHolder.tvUpdate.setOnClickListener(v -> {
            updateRouteBook(routeBook.getServerId(), i, view2, viewGroup);
        });
        return view2;
    }

    public void showDeleteDialog(final int i) {
        new BiciAlertDialogBuilder(this.context).setMessage("确定需要删除本地路书？")
                .setPositiveButton("删除", (dialogInterface, i2) -> {
                    if (RouteBookUtil.deleteRouteBook(routeBookList.get(i))) {
                        routeBookList.remove(i);
                        notifyDataSetChanged();
                        App.getContext().showMessage("删除成功");
                        if (routeBookList.isEmpty()) {
                            App.getContext().sendBroadcast(new Intent(RouteBook.ACTION_DELETE_LUSHU));
                        }
                        return;
                    }
                    App.getContext().showMessage("删除失败");
                }).setNegativeButton("取消", (dialogInterface, i2) -> {
                }).show();
    }

    private void updateRouteBook(long serverId, int i, View view, ViewGroup viewGroup) {
        ((BaseActivity) context).showLoadingDialog(R.string.update, true);
        MyHttpClient.requestLushuInfo(serverId, REQUEST_TYPE_ROUTE_BOOK_INFO, new BiCiCallback() {
            @Override
            public void onResponseString(@NonNull String str) {
                try {
                    JSONObject jsonObject = new JSONObject(str);
                    JSONObject jsonObjectData = jsonObject.getJSONObject("data");
                    Log.d("updateRouteBook data = " + jsonObjectData);
                    RouteBook routeBook = RouteBook.parseLushuByServer(jsonObjectData, true);
                    routeBook.save();
                    routeBookList.set(i, routeBook);
                    view.post(() -> {
                        getView(i, view, viewGroup);
                    });
                    ((BaseActivity) context).dismissLoadingDialog();
                } catch (JSONException e) {
                    ((BaseActivity) context).dismissLoadingDialog();
                    e.printStackTrace();
                }
            }

            @Override
            public void onResponseFail(String str3) {
                super.onResponseFail(str3);
                ((BaseActivity) context).dismissLoadingDialog();
            }
        });
    }

    @Override
    public Object getItem(int i) {
        return this.routeBookList.get(i);
    }

    @Override
    public int getCount() {
        return this.routeBookList.size();
    }

    private void importRouteBook(long serverId) {
        if (context instanceof RouteBookImportActivity routeBookImportActivity) {
            routeBookImportActivity.showLoadingDialog(R.string.syncing_workout, routeBookImportActivity);
        }
        MyHttpClient.downloadRouteBookFile(serverId, new BiCiCallback() {
            @Override
            public void onResponseString(@NonNull String s) throws JSONException {
                RouteBookInfo routeBookInfo;

                try {
                    JSONObject jsonObject = new JSONObject(s);
                    String msg = jsonObject.getString("msg");
                    String ext = jsonObject.getString("ext");
                    String content = jsonObject.getString("content");
                    String json_url = jsonObject.getString("name");
                    double distance = jsonObject.getDouble("distance");
                    int size = jsonObject.getInt("fileSize");
                    String type = jsonObject.getString("sportType");
                    String version = jsonObject.getString("version");
                    int source = jsonObject.getInt("sourceType");
                    int gain = (int) jsonObject.getDouble("elevationGain");
                    String title = jsonObject.getString("title");
                    String filePath = RouteBookUtil.saveDirectionFile(content, serverId, ext);

                    android.util.Log.d(TAG, " the routebook serverId is: " + serverId);
                    android.util.Log.d(TAG, " the routebook filePath is: " + filePath);
                    List<RouteBookInfo> list =
                            LitePal.where("serverId = ?", String.valueOf(serverId)).find(RouteBookInfo.class);
                    android.util.Log.d(TAG, " list.size is: " + list.size());

                    if (!list.isEmpty()) {
                        routeBookInfo = list.get(0);
                        android.util.Log.d(TAG, " the routebookinfo db exist,id: " + routeBookInfo.getId());
                    } else {
                        android.util.Log.d(TAG, " new the routebookinfo");
                        routeBookInfo = new RouteBookInfo();
                    }
                    routeBookInfo.setJson_url(json_url);
                    routeBookInfo.setTitle(title);
                    routeBookInfo.setDistance(distance);
                    routeBookInfo.setSourceType(source);
                    routeBookInfo.setSportType(type);
                    routeBookInfo.setElevationGain(gain);
                    routeBookInfo.setServerId(String.valueOf(serverId));
                    routeBookInfo.setFilePath(filePath);
                    routeBookInfo.setExt(ext);
                    routeBookInfo.save();
                    // end by wangsm

                    // if the device is connected,will update the routebooks.json,send routebooks.json,send the
                    // routebook file to device.
                    Route newRoute = new Route(null, null, json_url, title, String.valueOf(serverId), distance, type,
                            -1, version, false, source, gain);
                    newRoute.setExt(ext);
                    android.util.Log.d(TAG, " route information ,begin write the routebooks.json,s: " + s);
                    // add by wangsm for update routebooks.json
                    android.util.Log.d(TAG, " route information,serverId: " + serverId);
                    ProtocolPresenter protocolPresenter = ProtocolPresenter.getInstance();
                    if (protocolPresenter != null) {
                        ProtocolService protocolService = protocolPresenter.getProtocolService();
                        if (protocolService == null) {
                            android.util.Log.d(TAG, " pls connect the device ");
                            if (context instanceof RouteBookImportActivity routeBookImportActivity) {
                                routeBookImportActivity.runOnUiThread(routeBookImportActivity::dismissLoadingDialog);
                            }
                            return;
                        }
                        int state = protocolService.getDeviceConnectState();
                        if (protocolService.isConnect && state == BluetoothProfile.STATE_CONNECTED) {
                            if (context instanceof RouteBookImportActivity routeBookImportActivity) {
                                Routebooks routebooks = FileUtils.parseRouteBooksJson(routeBookImportActivity);
                                android.util.Log.d(TAG, " the device is connected,update the routebook.json to send ");
                                List<Route> routes = null;
                                if (routebooks == null) {
                                    routes = new ArrayList<>();
                                    routes.add(newRoute);
                                    // FileUtils.createRouteBooks(infoView.getActivity(), routes);
                                } else {
                                    routes = routebooks.routes;
                                    int index = 0;
                                    for (index = 0; index < routes.size(); index++) {
                                        Route route = routes.get(index);
                                        android.util.Log.d(TAG, " the route rid:" + route.getRid());
                                        if (route.getRid().equals(String.valueOf(serverId))) {
                                            android.util.Log.d(TAG, " set new route");
                                            routes.set(index, newRoute);
                                            break;
                                        }
                                    }
                                    // Route newRoute = new Route(null,null, json_url, title, String.valueOf(serverId),
                                    // size, type, -1, version, false,source,gain);
                                    android.util.Log.d(TAG, " the route list index: " + index);
                                    android.util.Log.d(TAG, " the route list size: " + routes.size());
                                    if (index == routes.size()) {
                                        android.util.Log.d(TAG, " add new route");
                                        routes.add(newRoute);
                                    }
                                    /*
                                     * boolean result = FileUtils.createRouteBooks(infoView.getActivity(), routes);
                                     * if(result){ Log.d(TAG," begin send the routebooks.json"); //filePath List<String>
                                     * filePathList = new ArrayList<>(); filePathList.add(filePath);
                                     * FileUtils.sendRouteBooksJsonFile(infoView.getActivity(),protocolPresenter,
                                     * filePathList); }
                                     */
                                }
                                boolean result = FileUtils.createRouteBooks(routeBookImportActivity, routes);
                                if (result) {
                                    android.util.Log.d(TAG, " begin send the routebooks.json");
                                    // filePath
                                    List<String> filePathList = new ArrayList<>();
                                    filePathList.add(filePath);
                                    FileUtils.sendRouteBooksJsonFile(routeBookImportActivity, protocolPresenter,
                                            filePathList);
                                }
                            }
                        } // protocolService != null && protocolService.isConnect
                    } // protocolPresenter != null
                      // end by wangsm*/

                } catch (JSONException e) {
                    e.printStackTrace();
                    if (context instanceof RouteBookImportActivity routeBookImportActivity) {
                        routeBookImportActivity.toast(R.string.toast_download_failed);
                    }
                }
            }
        });
    }

    /*
     * //if error may be download the local routebook files. private void syncRouteBookToDevice(long serverId){
     *
     * RouteBookInfo routeBookInfo = null; //add by wangsm for save routebook info into db.
     * Log.d(TAG," syncRouteBookToDevice, serverId is: " + serverId); List<RouteBookInfo> list =
     * LitePal.where("serverId = ?",String.valueOf(serverId)).find(RouteBookInfo.class); //Log.d(TAG," list.size is: " +
     * list.size());
     *
     * if(list != null && list.size() > 0){ routeBookInfo = list.get(0); Log.d(TAG," the routebookinfo db exist,id: " +
     * routeBookInfo.getId()); Route newRoute = new Route(null,null, routeBookInfo.getJson_url(),
     * routeBookInfo.getTitle(), String.valueOf(serverId), routeBookInfo.getFileSize(), routeBookInfo.getSportType(),
     * -1, routeBookInfo.getVersion(), false,routeBookInfo.getSourceType(),routeBookInfo.getElevationGain());
     * syncRouteBookToDevice(serverId,newRoute); }
     *
     * //if the device is connected,will update the routebooks.json,send routebooks.json,send the routebook file to
     * device.
     *
     * //end by wangsm }
     *
     * private void syncRouteBookToDevice(long serverId,Route newRoute){
     *
     * if(newRoute == null){ return; }
     *
     * ProtocolPresenter protocolPresenter = ProtocolPresenter.getInstance(); if(protocolPresenter != null){
     * ProtocolService protocolService = protocolPresenter.getProtocolService(); if(protocolService != null &&
     * protocolService.isConnect){ Routebooks routebooks = FileUtils.parseRouteBooksJson(infoView.getActivity());
     * Log.d(TAG," the device is connected,update the routebook.json to send "); if(routebooks == null){ List<Route>
     * routes = new ArrayList<>(); routes.add(newRoute); FileUtils.createRouteBooks(infoView.getActivity(), routes);
     * }else{ List<Route> routes = routebooks.getRoutes(); int index = 0; for(index =0; index < routes.size(); index++){
     * Route route = routes.get(index); Log.d(TAG," the route rid:" + route.getRid());
     * if(route.getRid().equals(String.valueOf(serverId))){ Log.d(TAG," set new route"); routes.set(index,newRoute);
     * break; } } //Route newRoute = new Route(null,null, json_url, title, String.valueOf(serverId), size, type, -1,
     * version, false,source,gain); Log.d(TAG," the route list index: " + index); Log.d(TAG," the route list size: " +
     * routes.size()); if(index == routes.size()){ Log.d(TAG," add new route"); routes.add(newRoute); } boolean result =
     * FileUtils.createRouteBooks(infoView.getActivity(), routes); if(result){
     * Log.d(TAG," begin send the routebooks.json");
     * FileUtils.sendRouteBooksJsonFile(infoView.getActivity(),protocolPresenter); } } }else{
     * Log.d(TAG," device disconnected."); }//protocolService != null && protocolService.isConnect }//protocolPresenter
     * != null }
     */

    private void checkIfNotExistOnRouteBooks(long serverId, ImageView imageView) {
        try {
            new Thread(() -> {
                Routebooks routebooks = com.besall.allbase.common.utils.FileUtils.parseRouteBooksJson(context);
                boolean shouldHide = false;
                if (null != routebooks) {
                    List<Route> routeList = routebooks.routes;
                    if (!routeList.isEmpty()) {
                        for (Route route : routeList) {
                            if (route.getRid().equals(String.valueOf(serverId))) {
                                shouldHide = true;
                                break;
                            }
                        }
                    }
                }
                boolean finalShouldHide = shouldHide;
                imageView.post(() -> {
                    if (finalShouldHide) {
                        imageView.setVisibility(View.GONE);
                    }
                });
            }).start();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            Log.e("checkIfNotExistOnRouteBooks", throwable);
        }
    }

    static class ViewHolder {
        private CheckBox cbCheck;
        private ImageView ivDelete;
        private ImageView ivSportType;
        private ImageView ivMap;
        private ImageView ivTypeIcons;
        private TextView tvComment;
        private TextView tvDistance;
        private TextView tvDownload;
        private TextView tvLushuId;
        private TextView tvTitle;
        private TextView tvUpdate;
        private UserAvatarView userAvatarView;
        private TextView tvType;
        private Button btnImport;

        public ViewHolder(View view) {
            bindView(view);
        }

        private void bindView(View view) {
            this.ivMap = view.findViewById(R.id.ivMap);
            this.ivSportType = view.findViewById(R.id.ivSportType);
            this.cbCheck = view.findViewById(R.id.cbCheck);
            this.userAvatarView = view.findViewById(R.id.userAvatar);
            this.tvTitle = view.findViewById(R.id.tvTitle);
            this.tvDistance = view.findViewById(R.id.tvDistance);
            this.tvComment = view.findViewById(R.id.tvComment);
            this.tvDownload = view.findViewById(R.id.tvDownload);
            this.ivTypeIcons = view.findViewById(R.id.ivTypeIcons);
            this.tvLushuId = view.findViewById(R.id.tvLushuId);
            this.tvUpdate = view.findViewById(R.id.tvUpdate);
            this.ivDelete = view.findViewById(R.id.ivDelete);
            this.tvType = view.findViewById(R.id.tvLushuType);
            this.btnImport = view.findViewById(R.id.btnImport);
        }
    }
}
